import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
//非递归实现前序遍历
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();

        TreeNode cur=root;

        while(cur!=null||!stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                // System.out.println(cur.val+" ");
                res.add(cur.val);
                cur=cur.left;
            }
            cur=stack.pop();
            cur=cur.right;
        }
        return res;

    }
}

//实现非递归中序遍历
class Solution1 {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();

        TreeNode cur=root;
        while(cur!=null||!stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                cur=cur.left;
            }
            cur=stack.pop();
            // System.out.println(cur.val+" ");
            res.add(cur.val);
            cur=cur.right;

        }
        return res;
    }
}
//实现非递归后序遍历
class Solution2 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur=root;
        TreeNode prev=null;
        while(cur!=null||!stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                cur=cur.left;
            }
            TreeNode top=stack.peek();
            //top.right==prev避免死循环
            if(top.right==null||top.right==prev){
                stack.pop();
                res.add(top.val);
                prev=top;
            }
            else{
                cur=top.right;
            }

        }
        return res;

    }
}